<?php

namespace app\api\controller;
use PHPMailer\SendEmail;
use think\Controller;
use wechat\src\WeChat;
use think\Request;
use app\common\model\Qrcode;
use app\common\model\System;
use think\Db;

class Index extends Controller
{
    protected $wechat, $message, $request;

    public function __construct()
    {
        $this->request = Request::instance();
        $this->wechat = (new WeChat);
        $this->wechat->valid();

    }

    public function index()
    {
        $data['mailcode'] ='dsadasd';
        $html = <<<eor
        你大叔11111111{$this->request->domain()}
<a href="{$this->request->domain()}/user-Verification-mailcode-{$data['mailcode']}" >连接地址</a>
eor;
        echo $html;
        $dd = new SendEmail();
        $maildata =array(
            'to'=>'149529339@qq.com',
            'subject'=>'biaoti',
            'content'=>'gfdgdsfgsdfg',
            'mailname'=>'',
        );


        echo $dd->SendEmail('zhiqiang@iottogo.com',$this->request->domain(),$html,$maildata);
        exit();
        $instance = $this->wechat->instance('message');
        $this->message = $instance->getMessage();
        model('wuser')->save(['last_time' => time()], ['openid' => $this->message->FromUserName]);
        switch ($this->message->MsgType) {
            case 'text'://文本消息

                $this->keyword($this->message->Content, $this->message);
                break;
            case 'image'://图片消息
                $this->special('image', $this->message);
                break;
            case 'voice'://语音消息
                $this->special('voice', $this->message);
                break;
            case 'video'://视频消息
                $this->special('video', $this->message);
                break;
            case 'shortvideo'://小视频消息
                $this->special('shortvideo', $this->message);
                break;
            case 'location'://地理位置消息
                $this->special('location', $this->message);
                break;
            case 'link'://链接消息
                $this->special('link', $this->message);
                break;
            case 'event'://事件消息
                switch (strtolower($this->message->Event)) {
                    case 'subscribe'://关注
                        if (isset($this->message->Ticket)) {
                            if ($result = Qrcode::get(['ticket' => $this->message->Ticket])) {//通过生成场景二维码关注
                                //如需要扩展其它，代码在这里开始

                                if (!db('qrcode_data')
                                    ->where(['scene_id' => $result['scene_id'], 'openid' => $this->message->FromUserName])
                                    ->find()
                                ) {
                                    db('qrcode')
                                        ->where(['scene_id' => $result['scene_id']])
                                        ->setInc('gz_count');
                                }
                                $friendInfo = $this->UserInfo($this->message->FromUserName);

                                if (!empty($friendInfo)) {
                                    $friendModel = db('wuser');
                                    $Res = $friendModel->where(['openid' => $this->message->FromUserName])->find();
                                    if (empty($Res)) {
                                        $friendModel->insert($friendInfo);
                                    } else {
                                        $friendModel->where(['openid' => $this->message->FromUserName])->update($friendInfo);
                                    }
                                }
                                $this->qrcode($result, $this->message);
                            }elseif($redbao = db('redbao')->where('ticket',$this->message->Ticket)->find()){
                                $friendInfo = $this->UserInfo($this->message->FromUserName);

                                if (!empty($friendInfo)) {
                                    $friendModel = db('wuser');
                                    $Res = $friendModel->where(['openid' => $this->message->FromUserName])->find();
                                    if (empty($Res)) {
                                        $friendModel->insert($friendInfo);
                                    } else {
                                        $friendModel->where(['openid' => $this->message->FromUserName])->update($friendInfo);
                                    }
                                }

                                //发送红包
                                $this->redbao($redbao ,$friendInfo);


                            }
                        }

                        $this->subscribe($this->message);
                        break;
                    case 'unsubscribe'://取关
                        model('wuser')->save(['subscribe' => '0', 'unsubscribe_time' => time()], ['openid' =>  $this->message->FromUserName]);

                        // $this->subscribe($this->message, 'unsubscribe');
                        break;
                    case 'scan'://用户扫码已关注时的事件推送
                        if ($result = Qrcode::get(['ticket' => $this->message->Ticket])) {
                            //注意，没有关过的粉丝第一次扫码关注不走这里
                            //1:通过场景二维码关注
                            $this->qrcode($result, $this->message);
                        }elseif($redbao = db('redbao')->where('ticket',$this->message->Ticket)->find()){
                            $friendInfo = $this->UserInfo($this->message->FromUserName);

                            if (!empty($friendInfo)) {
                                $friendModel = db('wuser');
                                $Res = $friendModel->where(['openid' => $this->message->FromUserName])->find();
                                if (empty($Res)) {
                                    $friendModel->insert($friendInfo);
                                } else {
                                    $friendModel->where(['openid' => $this->message->FromUserName])->update($friendInfo);
                                }
                            }
                            //发送红包
                            $this->redbao($redbao ,$friendInfo);
                        }
                        break;
                    case 'location':     // 上报地理位置事件 event_location
                        $this->special('event_location', $this->message);
                        break;
                    case 'click'://自定义菜单事件

                        $this->keyword($this->message->EventKey, $this->message);
                        break;
                    case 'view'://点击菜单跳转链接时的事件推送
                        $this->special('view', $this->message);
                        break;
                    default:
                        //
                        break;
                }
                break;
            default:
                //
                break;
        }
        //终止执行
        exit;
    }



    /*
        public function index2222()
        {
            $instance = $this->wechat->instance('message');
            $this->message = $instance->getMessage();

            //判断是否是文本消息
            if ($instance->isTextMsg()) {
                //向用户回复消息
                $new = model('article')->where('wechatkey', $this->message->Content)->find();
                if ($new) {
                    //向用户回复消息
                    $news = array(
                        array(
                            'title' => $new->title,
                            'discription' => $new->miaoshu,
                            'picurl' => $this->request->domain() . '/public/uploads' . ($new->image ? '/image/' . $new->image : 'sm_nopic.jpg'),
                            'url' => $this->request->domain() . url('mobile/article/detailed', array('id' => $new->id, 'navid' => $new->cid)),
                        ),
                    );
                    $instance->news($news);
                }

                $this->wechatmessage_save($this->message->FromUserName);

                $wechatmessageread = array(
                    'openid' => $this->message->FromUserName,
                    'who' => 0,
                    'center' => $this->message->Content,
                    'mtype' => 'text',
                    'create_time' => time()
                );
                model('wechatmessageread')->save($wechatmessageread);

                if(model('wechatmessage')->save(['create_time'=>time(),'status'=>'0'],['openid'=>$this->message->FromUserName])){
                    $instance->text('我们已经收到你的信息！等待回复');
                }

            }

            //点击关键词回复
            if ($instance->isClickEvent()) {
                //向用户回复消息
                $new = model('article')->where('issue', $this->message->EventKey)->find();
                if ($new) {
                    //向用户回复消息
                    $news = array(
                        array(
                            'title' => $new->title,
                            'discription' => $new->miaoshu,
                            'picurl' => $this->request->domain() . '/public/uploads' . ($new->image ? '/image/' . $new->image : 'sm_nopic.jpg'),
                            'url' => $this->request->domain() . url('mobile/article/detailed', array('id' => $new->id, 'navid' => $new->cid)),
                        ),
                    );
                    $instance->news($news);
                }
            }

            //判断是否是图片消息
            if ($instance->isImageMsg()) {
                $this->wechatmessage_save($this->message->FromUserName);
                $wechatmessageread = array(
                    'openid' => $this->message->FromUserName,
                    'who' => 0,
                    'center' => $this->message->PicUrl,
                    'mtype' => 'image',
                    'create_time' => time()
                );
                model('wechatmessageread')->save($wechatmessageread);

                if(!model('wechatmessage')->save(['create_time'=>time(),'status'=>'0'],['openid'=>$this->message->FromUserName])){
                    $instance->text('我们已经收到你的信息！等待回复');
                }

                //向用户回复消息
                $instance->text("图片url:{$this->message->PicUrl},图片MediaId: {$this->message->MediaId}");
            }

            //关注时回复消息
            if ($instance->isSubscribeEvent()) {
                //向用户回复消息
                $instance->text(cache('system_Wechat')['Event']['value']);
            }
        }
    */


    /**
     * 粉丝关注\取关
     * @author 
     */

    public function subscribe($msg = [], $type='subscribe')
    {

        $friendInfo = $this->UserInfo($msg->FromUserName);

        if (!empty($friendInfo)) {
            $friendModel = db('wuser');
            if ($type == 'subscribe') {
                $Res = $friendModel->where(['openid' => $msg->FromUserName])->find();
                if (empty($Res)) {

                    $friendModel->insert($friendInfo);
                } else {
                    $friendModel->where(['openid' => $msg->FromUserName])->update($friendInfo);

                }
            } elseif ($type == 'unsubscribe') {
                $friendModel->where(['openid' =>  $msg->FromUserName])->update(['subscribe' => '0', 'unsubscribe_time' => time()]);
            }
        } else {//公众号没有权限获取用户基本信息 可按需求扩展
            if ($type == 'subscribe') {
                $this->wechat->instance('message')->text('4');
            } elseif ($type == 'unsubscribe') {
                $this->wechat->instance('message')->text('5');
            }
        }

        $rule = db('mp_rule')->where(['event' => 'subscribe'])->find();
        if (!empty($rule)) {
            if ($rule['keyword']) {
                $this->keyword($rule['keyword'], $msg);
            }
            if ($rule['addon']) {
//                loadAdApi($rule['addon'], $msg,['addon'=>$rule['addon']]);
            }
        }


    }

    /**
     * 消息处理
     * @author gEESON 
     * @param $msgData
     */
    public function mpMsg($msgData)
    {

        $this->wechatmessage_save($msgData->FromUserName);
        $model = model('wechatmessageread');

        switch ($msgData->MsgType) {
            case 'text'://文本消息
                $msg = array(
                    'openid' => $msgData->FromUserName,
                    'who' => 0,
                    'center' => $this->message->Content,
                    'mtype' => $msgData->MsgType,
                    'create_time' => time()
                );
//              $this->wechat->instance('message')->text($msg['content'].$msg['who']);
                $model->save($msg);
                break;
            case 'image'://图片消息
//                $msg['content'] = getHostDomain() . url('mp/Show/image', ['url' => urlencode($msgData['PicUrl'])]);
                $msg = array(
                    'openid' => $msgData->FromUserName,
                    'who' => 0,
                    'center' => $msgData->PicUrl,
                    'mtype' => $msgData->MsgType,
                    'create_time' => time()
                );
                $model->save($msg);
                break;
            case 'voice'://语音消息
                $msg = array(
                    'openid' => $msgData->FromUserName,
                    'who' => 0,
                    'center' => $msgData->MediaId,
                    'mtype' => $msgData->MsgType,
                    'create_time' => time()
                );
                $model->save($msg);
                break;
            case 'video'://视频消息
                $msg = array(
                    'openid' => $msgData->FromUserName,
                    'who' => 0,
                    'center' => $msgData->MediaId,
                    'mtype' => $msgData->MsgType,
                    'create_time' => time()
                );
                $model->save($msg);
                break;
            case 'shortvideo'://小视频消息

                break;
            case 'location'://地理位置消息
                $msg = array(
                    'openid' => $msgData->FromUserName,
                    'who' => 0,
                    'center' => $msgData->Label,
                    'mtype' => $msgData->MsgType,
                    'create_time' => time()
                );
                $model->save($msg);
                break;
            case 'link'://链接消息

                break;

        }

        model('wechatmessage')->save(['create_time' => time(), 'status' => '0'], ['openid' => $msgData->FromUserName]);
        exit;
    }

    /**
     * 关键词回复规则
     * @param $keyword 消息文本
     * @author geeson 
     * @param $msg array 微信消息
     * case 回复类型 text,addon,images,news,voice,music,video
     *
     */
    public function keyword($keyword, $msg = [])
    {

        $rule = db('mp_rule')->where(['keyword' => $keyword, 'status' => '1'])
            ->where('event', 'null')
            ->order('id Desc')->find();
        if (!empty($rule)) {
            switch ($rule['type']) {//text,addon,images,news,voice,music,video
                case 'addon'://该关键词是插件应用响应的
//                    loadAdApi($rule['addon'], $msg,['addon'=>$rule['addon']]);
                    break;
                case 'text'://文本
                    $content = db('mp_reply')->where(['reply_id' => $rule['reply_id']])->field('content')->find();
                    $this->wechat->instance('message')->text($content['content']);
                    break;
                case 'image'://图片

                    $result = db('mp_reply')->where(['reply_id' => $rule['reply_id']])->find();

                    if (!empty($result)) {
                        // $this->wechat->instance('message')->text($result['media_id']);
                        $this->wechat->instance('message')->image($result['media_id']);
                    }
                    break;
                case 'news'://图文
                    $content = db('mp_reply')->where(['reply_id' => $rule['reply_id']])->select();

                    $news = [];
                    foreach ($content as $key1 => $v) {
                        foreach ($v as $key2 => $v) {
                            if ($key2 == 'title') {
                                $news[$key1]['title'] = $v;
                            }
                            if ($key2 == 'content') {
                                $news[$key1]['discription'] = $v;
                            }
                            if ($key2 == 'url') {
                                $news[$key1]['picurl'] = $this->request->domain() . '/public/uploads/addkey/' . $v;
                            }
                            if ($key2 == 'link') {
                                $news[$key1]['url'] = $v;
                            }

                        }
                    }
                    $this->wechat->instance('message')->news($news);

                    break;
                case 'voice'://语音
                    $result = db('mp_reply')->where(['reply_id' => $rule['reply_id']])->find();
                    if (!empty($result)) {
                        $this->wechat->instance('message')->voice($result['media_id']);
                    }
                    break;
                case 'music'://音乐
                    $result = db('mp_reply')->where(['reply_id' => $rule['reply_id']])->find();
                    if (is_array($result)) {
                        $music = array(
                            'title' => $result['title'],
                            'description' => $result['content'],
                            'musicurl' => $result['url'],
                            'hqmusicurl' => $result['url'],
                        );

                        $this->wechat->instance('message')->music($music);
                    }
                    break;
                case 'video'://视频
                    $result = db('mp_reply')->where(['reply_id' => $rule['reply_id']])->find();
                    if (!empty($result)) {
                        $video = array(
                            'media_id' => $result['media_id'],
                            'title' => $result['title'],
                            'description' => $result['content'],

                        );
                        //$this->wechat->instance('message')->text($video['media_id'].'   '.$video['description'].'   '.$video['title']);
                        $this->wechat->instance('message')->video($video);
                    }
                    break;
                case 'member'://视频
                    $content = db('mp_reply')->where(['reply_id' => $rule['reply_id']])->select();
                    $news = [];
                    foreach ($content as $key1 => $v) {
                        foreach ($v as $key2 => $v) {
                            if ($key2 == 'title') {
                                $news[$key1]['Title'] = '会员登录';
                            }
                            if ($key2 == 'url') {
                                $news[$key1]['picurl'] = $this->request->domain() . '/public/uploads/addkey/' . $v;
                            }
                            if ($key2 == 'link') {
                                $news[$key1]['url'] = $v;
                            }
                        }
                    }
                    $this->wechat->instance('message')->news($news);
                    break;
                default:
                    //
                    break;
            }
        } else {

            $rule = db('mp_rule')
                ->where(['event' => 'unidentified', 'status' => '1'])->find();
            if (!empty($rule)) {
                if ($rule['keyword']) {
                    $this->keyword($rule['keyword'], $msg);
                }
                if ($rule['addon']) {
//                    loadAdApi($rule['addon'], $msg,['addon'=>$rule['addon']]);
                }
            } else {
                $this->mpMsg($msg);
            }

        }

    }

    /**
     * 处理特殊事件
     *
     * $type 事件类型
     * $msgData 微信服务器发来消息
     */
    public function special($type, $msgData)
    {
        $rule = db('mp_rule')
            ->where(['event' => $type, 'status' => '1'])->find();
        if (!empty($rule)) {
            if ($rule['keyword']) {
                $this->keyword($rule['keyword'], $msgData);
            }
            if ($rule['addon']) {
//                loadAdApi($rule['addon'], $msgData,['addon'=>$rule['addon']]);
            }
        } else {//不存在响应处理
            $rule = db('mp_rule')
                ->where(['event' => 'unidentified', 'status' => '1'])->find();
            if (!empty($rule)) {
                if ($rule['keyword']) {
                    $this->keyword($rule['keyword'], $msgData);
                }
                if ($rule['addon']) {
//                    loadAdApi($rule['addon'], $msgData,['addon'=>$rule['addon']]);
                }
            } else {
                $this->mpMsg($msgData);
            }

        }
    }






    /**
     * 扫码关注/扫码事件
     *
     * @param $result array 场景二维码数组
     * @param $msgData array 微信服务器发来数组
     */
    public function qrcode($result = [], $msgData = [])
    {

        $data = [];
        if ($result = Qrcode::get(['ticket' => $msgData->Ticket])) {
            Qrcode::where(['ticket' => $msgData->Ticket])
                ->setInc('scan_count');
            $data['scene_id'] = $result['scene_id'];
            $data['openid'] = $msgData->FromUserName;
            $data['create_time'] = time();
            $data['qrcode_id'] = $result['id'];
            if (db('qrcode_data')->where(['scene_id' => $data['scene_id'], 'openid' => $data['openid']])->find()) {
                db('qrcode_data')
                    ->where(['scene_id' => $data['scene_id'], 'openid' => $data['openid']])
                    ->setInc('scan_count');
            } else {
                $data['type'] = '1';
                db('qrcode_data')->insert($data);
            }
        }
        // $Msg = array_merge($msgData, $data);

        $this->keyword($result['keyword'], $msgData);
    }

    /**
     * @param $openid
     *添加用户会话列表是否存在
     */
    public function wechatmessage_save($openid)
    {

        if (!model('wechatmessage')->where('openid', $openid)->find()) {
            $userinfo = (new WeChat)->instance('user')->getUserInfo($openid);
            $data = array(
                'openid' => $userinfo['openid'],
                'nickname' => $userinfo['nickname'],
                'sex' => $userinfo['sex'],
                'city' => $userinfo['city'],
                'province' => $userinfo['province'],
                'headimgurl' => $userinfo['headimgurl'],
                'create_time' => time()
            );
            model('wechatmessage')->save($data);

        }
    }

    /**
     *用户信息
     */
    public function UserInfo($FromUserName){
        $userinfo = (new WeChat)->instance('user')->getUserInfo($FromUserName);
        return $friendInfo = array(
            'openid' => $userinfo['openid'],
            'groupid' => $userinfo['groupid'],
            'subscribe' => $userinfo['subscribe'],
            'nickname' => $userinfo['nickname'],
            'sex' => $userinfo['sex'],
            'city' => $userinfo['city'],
            'country' => $userinfo['country'],
            'province' => $userinfo['province'],
            'headimgurl' => $userinfo['headimgurl'],
            'subscribe_time' => $userinfo['subscribe_time'],
            //'create_time' => time()
        );
    }


    /**
     * 发送红包
     */
    public function redbao($result,$msgData){
        if ($result['state'] == '0'){
            $data = array(
                'state'=>1,
                'name'=>$msgData['nickname'],
                'openid'=>$msgData['openid'],
                'image'=>$msgData['headimgurl'],
                'get_time'=>time()
            );
            db('redbao')->where('ticket', $result['ticket'])->update($data);

            $this->wechat->instance('message')->text('恭喜你领了'.$result['money'].'元红包');
        }elseif($result['state'] == '1'){
            $this->wechat->instance('message')->text('红包已被'.$result['name'].'-'.date('Y-m-d H:i:s',$result['get_time']).'领取了');
        }else{
            $this->wechat->instance('message')->text('谢谢你的参与，本次没有中将');
        }
    }

    public function dd(){
        $data = [
            //商户名称
            'send_name'    => '后盾网HDCMS',
            //付款金额,单位分,必须大于1元小于200元
            'total_amount' => 100,
            //红包发放总人数
            'total_num'    => '1',
            //红包祝福语
            'wishing'      => '恭喜发财',
            //活动名称
            'act_name'     => '开学红包',
            //红包祝福语
            'wishing'      => '祝同学们学业有成,心想事成',
            //备注
            'remark'       => '新班开课红包鼓励',
        ];

//        $user = $this->wechat->instance('oauth')->snsapiBase();
//        $data['re_openid'] = $user['openid'];
        $dd = $this->wechat->instance('cash')->sendRedPack($data);
        dump($dd);
    }
}
